# -*- coding: UTF-8 -*-
'''
@Project: stock
@File: PyCurl.py
@Notes: 
@Author: zhuyoucheng
@Date: 2021/4/1 0001 17:14
'''

import pycurl
from io import BytesIO
import json


class PyCurl(object):

    def get(self, url, header=['Content-Type: application/json']):
        ###创建curl对象###
        curl = pycurl.Curl()
        curl.fp = BytesIO()  # 设置IO，py3要求使用对bytes操作的BytesIO
        curl.setopt(curl.URL, url)  # (网址)
        curl.setopt(curl.HTTPHEADER, header)  # 网址头部
        curl.setopt(curl.POST, 0)  # 1表示调用post方法而不是get
        # curl.setopt(pycurl.POSTFIELDS, data)  # 数据
        # c.setopt(pycurl.WRITEFUNCTION, my_func)  # 返回数据，进行回调
        curl.setopt(curl.CONNECTTIMEOUT, 60)  # 超时中断
        curl.setopt(curl.TIMEOUT, 60)  # 下载超时
        curl.setopt(curl.WRITEFUNCTION, curl.fp.write)  # 将返回的内容定向到回调函数crl.fp.write，作用是将内容写入crl.fp
        curl.perform()  # 提交
        result = json.loads(curl.fp.getvalue())#加载json格式内容
        print(result)
        return result

    def post(self, url, data ,header):
        curl = pycurl.Curl()
        curl.fp = BytesIO()  # 设置IO，py3要求使用对bytes操作的BytesIO
        curl.setopt(curl.URL, url)  # (网址)
        curl.setopt(curl.HTTPHEADER, header)  # 网址头部
        curl.setopt(curl.POST, 1)  # 1表示调用post方法而不是get
        curl.setopt(curl.POSTFIELDS, data)  # 数据
        # c.setopt(pycurl.WRITEFUNCTION, my_func)  # 返回数据，进行回调
        curl.setopt(curl.CONNECTTIMEOUT, 60)  # 超时中断
        curl.setopt(curl.TIMEOUT, 60)  # 下载超时
        curl.setopt(curl.WRITEFUNCTION, curl.fp.write)  # 将返回的内容定向到回调函数crl.fp.write，作用是将内容写入crl.fp
        curl.perform()  # 提交
        result = json.loads(curl.fp.getvalue())  # 加载json格式内容
        print(result)
        return result
        pass